package com.rzico.core.plugin.anubis;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.model.PluginAttribute;
import com.rzico.core.plugin.RiderPlugin;
import com.rzico.core.rider.RiderApiProduct;
import com.rzico.core.rider.RiderApiRequest;
import com.rzico.core.rider.RiderApiResponse;
import com.rzico.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.guerlab.sdk.anubis.AnubisConstants;
import net.guerlab.sdk.anubis.accesstoken.AccessTokenManager;
import net.guerlab.sdk.anubis.client.AnubisClient;
import net.guerlab.sdk.anubis.client.impl.DefaultAnubisClient;
import net.guerlab.sdk.anubis.config.AnubisAutoConfiguration;
import net.guerlab.sdk.anubis.entity.*;
import net.guerlab.sdk.anubis.helper.NotifyHelper;
import net.guerlab.sdk.anubis.request.CarrierQueryRequest;
import net.guerlab.sdk.anubis.request.OrderCancelRequest;
import net.guerlab.sdk.anubis.request.OrderCreateRequest;
import net.guerlab.sdk.anubis.request.OrderQueryRequest;
import net.guerlab.sdk.anubis.response.CarrierQueryResponse;
import net.guerlab.sdk.anubis.response.OrderCancelResponse;
import net.guerlab.sdk.anubis.response.OrderCreateResponse;
import net.guerlab.sdk.anubis.response.OrderQueryResponse;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Component("anubisDeliverPlugin")
@Slf4j
public class AnubisDeliverPlugin extends RiderPlugin {

    @Override
    public String getName() {
        return "蜂鸟配送";
    }


    @Override
    public String getVersion() {
        return "1.0";
    }

    @Value("${sdk.anubis.app-id}")
    public static String APP_ID;
    /**
     * 应用密钥
     */
    @Value("${sdk.anubis.secret-key}")
    public static String SECRET_KEY;
    /**
     * 请求客户端对象
     */
    public static final AnubisClient CLIENT = new DefaultAnubisClient(APP_ID, SECRET_KEY, AnubisConstants.HOST_DEV,
            AnubisAutoConfiguration.createHttpClient(), new ObjectMapper());

    static {
        AccessTokenManager.instance().setClient(CLIENT);
    }

    @Override
    public RiderApiResponse addOrder(SysPlugin sysPlugin, RiderApiRequest riderApiRequest) {
        TransportInfo transportInfo = new TransportInfo();
        transportInfo.setTransportName(riderApiRequest.getShopName());//门店名称
        transportInfo.setTransportAddress(riderApiRequest.getShopAddress());//取货点地址
        transportInfo.setTransportLongitude(BigDecimal.valueOf(riderApiRequest.getShopLng()));//取货点经度
        transportInfo.setTransportLatitude(BigDecimal.valueOf(riderApiRequest.getShopLat()));//取货点维度
        transportInfo.setPositionSource(3);//1、腾讯地图，2、百度地图，3、高德地图
        transportInfo.setTransportTel(riderApiRequest.getShopPhone());//取货点联系方式
        //transportInfo.setTransportRemark("备注");//取货点备注


        ReceiverInfo receiverInfo = new ReceiverInfo();
        receiverInfo.setReceiverName(riderApiRequest.getConsignee());//收货人姓名
        receiverInfo.setReceiverPrimaryPhone(riderApiRequest.getPhone());//联系电话
        //receiverInfo.setReceiverSecondPhone("13911111111");//备用电话
        receiverInfo.setReceiverAddress(riderApiRequest.getAddress());//收货人地址
        receiverInfo.setReceiverLongitude(BigDecimal.valueOf(riderApiRequest.getLng()));//收货人经度
        receiverInfo.setReceiverLatitude(BigDecimal.valueOf(riderApiRequest.getLat()));//收货人纬度
        receiverInfo.setPositionSource(3);//1、腾讯地图，2、百度地图，3、高德地图
        //添加商品列表
        List<ItemInfo> itemInfos = new ArrayList<>(1);
        List<RiderApiProduct> productList=riderApiRequest.getProductList();
        ItemInfo itemInfo = new ItemInfo();
        for (RiderApiProduct r:productList) {
            //itemInfo.setItemId(r.getSn());//商品编号
            itemInfo.setItemName(r.getName());//商品名称
            itemInfo.setItemQuantity(r.getQuantity().intValue());//商品数量（转整形）
            itemInfo.setItemPrice(BigDecimal.valueOf(0));//商品实际支付金额
            itemInfo.setItemActualPrice(BigDecimal.valueOf(0));//商品原价
            //itemInfo.setItemSize(1);//商品尺寸
            //itemInfo.setItemRemark("商品备注");//商品备注
            itemInfo.setIsNeedPackage(0);//是否需要ele打包0、否1、是

            itemInfo.setIsAgentPurchase(0);//是否代购 0:否

            itemInfos.add(itemInfo);
        }

        AnubisOrderAddInfo anubisOrderAddInfo = new AnubisOrderAddInfo();
        anubisOrderAddInfo.setPartnerOrderCode(riderApiRequest.getOrderSn());//订单号
        anubisOrderAddInfo.setNotifyUrl(getNotifyUrl(sysPlugin));//回调地址
        anubisOrderAddInfo.setTransportInfo(transportInfo);//取货点
        //anubisOrderAddInfo.setOrderAddTime(System.currentTimeMillis());//下单时间
        anubisOrderAddInfo.setOrderTotalAmount(riderApiRequest.getAmountPayable());//订单总额
        anubisOrderAddInfo.setOrderActualAmount(BigDecimal.valueOf(0));//客户需付金额
        anubisOrderAddInfo.setOrderWeight(riderApiRequest.getWeight());//订单总重量
        //anubisOrderAddInfo.setOrderRemark("订单备注");//用户备注
        anubisOrderAddInfo.setIsInvoiced(0);// 是否需要发票0：不需要；1：需要
        //anubisOrderAddInfo.setInvoice("xxx公司");//发票抬头
        anubisOrderAddInfo.setOrderPaymentStatus(1);//支付状态0、未支付1、已支付
        anubisOrderAddInfo.setOrderPaymentMethod(1);//1、在线支付
        anubisOrderAddInfo.setIsAgentPayment(0);// 是否需要承运商代收货款 0：否
        //anubisOrderAddInfo.setRequirePaymentPay(BigDecimal.valueOf(50.00));//需要代收客户金额时必填
        anubisOrderAddInfo.setGoodsCount(riderApiRequest.getQuantity().intValue());//订单货物件数(转整形)
        //anubisOrderAddInfo.setRequireReceiveTime(System.currentTimeMillis() + 1000 * 60);//需要送达时间
        anubisOrderAddInfo.setSerialNumber(riderApiRequest.getNum());//订单流水号
        anubisOrderAddInfo.setReceiverInfo(receiverInfo);//收货人信息
        anubisOrderAddInfo.setItemInfos(itemInfos);//商品信息

        anubisOrderAddInfo.setChainStoreCode(riderApiRequest.getShopNo());//门店编号（支持数字、字母的组合）
        anubisOrderAddInfo.setOrderType(3);//订单类型（1:即时单，3:预约单）

        OrderCreateRequest request = new OrderCreateRequest();
        request.setAnubisOrder(anubisOrderAddInfo);
        OrderCreateResponse response = CLIENT.execute(request);

        if(response.getCode()==200){
        //查询订单  order_total_delivery_cost	decimal	配送费
        OrderQueryRequest feeRequest = new OrderQueryRequest();
        feeRequest.setPartnerOrderCode(riderApiRequest.getOrderSn());
        OrderQueryResponse feeResponse = CLIENT.execute(feeRequest);
        if(feeResponse.getCode()==200){
        AnubisOrderQueryInfo anubisOrderQueryInfo=feeResponse.getData();

        RiderApiResponse riderApiResponse=new RiderApiResponse();
        riderApiResponse.setOrderSn(riderApiRequest.getOrderSn());
        int status=orderStatus(anubisOrderQueryInfo.getOrderStatus());
        riderApiResponse.setStatusCode(status);
        riderApiResponse.setFee(anubisOrderQueryInfo.getOrderTotalDeliveryCost());
        riderApiResponse.setCode(0);
        return riderApiResponse;
        }
        else {
            return RiderApiResponse.error(response.getCode(),response.getMsg(),riderApiRequest.getOrderSn());
        }
        }
        else {
            return RiderApiResponse.error(response.getCode(),response.getMsg(),riderApiRequest.getOrderSn());
        }
    }

    /**
     * 计算运费
     */
    @Override
    public  RiderApiResponse calculateFee(SysPlugin sysPlugin, RiderApiRequest riderApiRequest) {
        //查询订单
        OrderQueryRequest queryRequest = new OrderQueryRequest();
        queryRequest.setPartnerOrderCode(riderApiRequest.getOrderSn());
        OrderQueryResponse queryResponse = CLIENT.execute(queryRequest);
        if(queryResponse.getCode()==200){
            RiderApiResponse riderApiResponse=new RiderApiResponse();
            AnubisOrderQueryInfo anubisOrderQueryInfo=queryResponse.getData();

            riderApiResponse.setOrderSn(riderApiRequest.getOrderSn());
            riderApiResponse.setFee(anubisOrderQueryInfo.getOrderTotalDeliveryCost());
            riderApiResponse.setCode(0);
            return riderApiResponse;
        }
        else{
            return RiderApiResponse.error(queryResponse.getCode(),queryResponse.getMsg(),riderApiRequest.getOrderSn());
        }
    }

    /**
     * 订单取消
     * @param  sn 订单号，cancelReason 取消原因 , cancelReasonId 取消原因ID
     * @return
     */
    @Override
    public  RiderApiResponse cancel(SysPlugin sysPlugin, String sn,String cancelReason,Integer cancelReasonId) {
        CancelInfo cancelInfo = new CancelInfo();
        cancelInfo.setOrderCancelCode(cancelReasonId);//取消原因
        cancelInfo.setOrderCancelDescription(cancelReason);//取消描述
        cancelInfo.setOrderCancelReasonCode(2);//订单取消原因代码(1:用户取消,2:商家取消)
        cancelInfo.setOrderCancelTime(System.currentTimeMillis());//取消时间
        cancelInfo.setPartnerOrderCode(sn);//订单号

        OrderCancelRequest request = new OrderCancelRequest();
        request.setCancelInfo(cancelInfo);

        OrderCancelResponse response = CLIENT.execute(request);

        if(response.getCode()==200){
            //查询订单
            OrderQueryRequest queryRequest = new OrderQueryRequest();
            queryRequest.setPartnerOrderCode(sn);
            OrderQueryResponse queryResponse = CLIENT.execute(queryRequest);
            if(queryResponse.getCode()==200){
            RiderApiResponse riderApiResponse=new RiderApiResponse();
            AnubisOrderQueryInfo anubisOrderQueryInfo=queryResponse.getData();

            riderApiResponse.setOrderSn(sn);
            int status=orderStatus(anubisOrderQueryInfo.getOrderStatus());
            riderApiResponse.setStatusCode(status);
            riderApiResponse.setCancel_from(cancelReasonId);
            riderApiResponse.setCode(0);
            return riderApiResponse;
            }
            else{
                return RiderApiResponse.error(queryResponse.getCode(),queryResponse.getMsg(),sn);
            }
        }
        else {
            return RiderApiResponse.error(response.getCode(),response.getMsg(),sn);
        }
    }

    /**
     * 查询订单详情   可跟踪骑手经纬度
     * @param sn
     * @return
     */
    @Override
    public  RiderApiResponse query(SysPlugin sysPlugin, String sn) {
        //查询订单
        OrderQueryRequest request = new OrderQueryRequest();
        request.setPartnerOrderCode(sn);
        OrderQueryResponse response = CLIENT.execute(request);
        if(response.getCode()==200){
            RiderApiResponse riderApiResponse=new RiderApiResponse();
            AnubisOrderQueryInfo anubisOrderQueryInfo=response.getData();

            riderApiResponse.setOrderSn(sn);
            int status=orderStatus(anubisOrderQueryInfo.getOrderStatus());
            riderApiResponse.setStatusCode(status);
            riderApiResponse.setFee(anubisOrderQueryInfo.getOrderTotalDeliveryCost());
            riderApiResponse.setDmName(anubisOrderQueryInfo.getCarrierDriverName());
            riderApiResponse.setDmMobile(anubisOrderQueryInfo.getCarrierDriverPhone());

            //骑手位置
            CarrierQueryRequest carrierRequest = new CarrierQueryRequest();
            request.setPartnerOrderCode(sn);
            CarrierQueryResponse carrierResponse = CLIENT.execute(carrierRequest);

            if(carrierResponse.getCode()==200){
                CarrierInfo carrierInfo=carrierResponse.getData();

                riderApiResponse.setLat(carrierInfo.getLatitude().doubleValue());
                riderApiResponse.setLng(carrierInfo.getLongitude().doubleValue());
                riderApiResponse.setCode(0);
                return riderApiResponse;

            }else
            {
                return RiderApiResponse.error(carrierResponse.getCode(),carrierResponse.getMsg(),sn);
            }

        }else{
            return RiderApiResponse.error(response.getCode(),response.getMsg(),sn);
        }

    }

    /**
     * 异常通知检查
     */
    @Override
    public  RiderApiResponse verifyNotify(SysPlugin sysPlugin, HttpServletRequest request) {
        //System.out.println("........................进入allnotify2.......................");
        RiderApiResponse riderApiResponse = null;
        try {
            riderApiResponse = new RiderApiResponse();
            StringBuffer body = new StringBuffer();
            InputStream in = request.getInputStream();
            BufferedInputStream buf = new BufferedInputStream(in);
            byte[] buffer = new byte[1024];
            int iRead;
            while ((iRead = buf.read(buffer)) != -1) {
                body.append(new String(buffer, 0, iRead, "UTF-8"));
            }

            ObjectMapper objectMapper = new ObjectMapper();
            NotifyHelper notifyHelper = new NotifyHelper();
            notifyHelper.setObjectMapper(objectMapper);

            System.out.println(notifyHelper.parseV2(body.toString()));
            NotifyInfo notifyInfo=notifyHelper.parseV2(body.toString());
            riderApiResponse.setOrderSn(notifyInfo.getPartnerOrderCode());
            int status=orderStatus(notifyInfo.getOrderStatus());
            riderApiResponse.setStatusCode(status);
            riderApiResponse.setDmMobile(notifyInfo.getCarrierDriverphone());
            riderApiResponse.setDmName(notifyInfo.getCarrierDriverName());
            String cancelReason=null;
            switch (notifyInfo.getCancelReason()){
                case 1:cancelReason = "用户取消订单";break;
                case 2:cancelReason = "商家取消订单";break;
                default:cancelReason="";
            }
            riderApiResponse.setMsg(cancelReason);
            riderApiResponse.setCode(0);
        } catch (Exception e) {
            RiderApiResponse riderApiResponse1 = new RiderApiResponse();
            riderApiResponse1.setCode(9999);
            riderApiResponse1.setMsg(e.getMessage());
            return riderApiResponse1;
        }
        return riderApiResponse;
    }

    //达达异常通知回复的字符串
    @Override
    public String getNotifyMessage(HttpServletRequest request) {

        return null;
    }

    //蜂鸟状态转达达状态码
    public int orderStatus(int anubisCode){
        int dadaCode=1;
        switch (anubisCode){
            case 1:dadaCode=1;break;
            case 2:dadaCode=3;break;
            case 3:dadaCode=4;break;
            case 4:dadaCode=5;break;
            case 20:
            case 80:dadaCode=2;break;
            default:dadaCode=7;
        }
        return dadaCode;
    }

}
